<template>
    <div class="ui-shade" v-show="showFilter" @click="shadeClose"
         :style="{'z-index':showFilter == 'detailFilter'?20:11}"></div>

    <header v-if="selectedSpu">
        <h1>{{selectedSpu.name}}</h1>
        <i @click="toggleFilterWindow"></i>
    </header>
    <header v-else>
        <div class="tab active" @click="toggle_cate"><span>{{selectedCate?selectedCate.name:'类别'}}</span></div>
        <div :class="['tab', selectedBrand._id?'active':'']" @click="toggle_brand"><span>{{selectedBrand._id?selectedBrand.name:'品牌'}}</span>
        </div>
        <i @click="toggle_detail"></i>
    </header>

    <div class="header-holder"></div>


    <!--<detail-filter v-if="showFilter == 'detailFilter'" keep-alive :selected_cate_id="selectedCate._id"-->
    <!--:selected_brand_id="selectedBrand._id" @change-spec="changeDetail"></detail-filter>-->

    <component :is="showFilter" keep-alive
               :selected_cate_id="showFilter == 'detailFilter'?selectedCate._id:mainCate._id"
               :selected_brand_id="selectedBrand._id"
               :selected_specs="selected_specs"

               @change-brand="changeBrand"
               @change-cate="changeCate"
               @change-spec="changeDetail"></component>

    <div class="list" v-dom="'topW'">
        <div v-for="val of list" class="product"
             v-link="{'name':'product','params':{'sku_id':val._id,spu_id:val.spu_id}}">

            <img :src="val.pics[0]+'?imageView2/1/w/200/h/200'">

            <div>
                <div class="thum-price">
                    <span v-if="val.price_cost" class="ui-price price-gray">{{val.price_cost/10}}</span>
                    <span class="ui-price price-red">{{val.price/10}}</span>
                </div>

                <div v-if="val.specs&&val.specs.length>0" class="specs">
                    <span v-for="specs of val.specs" class="spec">{{specs.spec_name}}:{{specs.specvalue_name}}</span>
                </div>

                <h1>
                    <b v-if="val.time_kill" class="seckill">秒杀</b>{{val.title}}
                </h1>

                <div v-if="val.state">
                    <div v-if="val.stock>0" class="tag-timer">
                        <span>{{val.time_kill | timeFormat 'h小时m分s后结束'}}</span>
                    </div>
                    <div v-if="val.stock==1&&val.time_kill>0" class="tag-timer">
                        <span>最后一件</span>
                    </div>
                    <div v-if="val.stock==0" class="tag-timer">
                        <span>秒杀结束</span>
                    </div>
                </div>
                <div v-if="val.state===0">
                    <div class="tag-timer">
                        <span>{{getSecKillDateStr(val)}}</span>
                    </div>
                </div>

                <div v-if="val.label&&val.length>0" class="tags">
                    <span v-for="label of val.label" class="tag">{{label}}</span>
                </div>
            </div>

        </div>
    </div>

    <div class="tips">
        {{canLoadMore?'正在加载更多':'没有更多产品'}}
    </div>

</template>

<script type="text/babel">
    import http from '../libs/http'
    import cateFilter from './productCateFilter.vue'
    import brandFilter from './productBrandFilter.vue'
    import detailFilter from './productDetailFilter.vue'
    import {dateFormat,timeFormat} from '../filters/dateFormat';

    var loadMoreTask, secKillTimer;
    var vm = {
        components: {
            cateFilter: cateFilter,
            brandFilter: brandFilter,
            detailFilter: detailFilter
        },
        data(){
            return {
                mainCate: {
                    _id: '',
                    name: '',
                    subCate: {
                        name: '',
                        _id: ''
                    }
                },
                selectedBrand: {
                    _id: '',
                    name: ''
                },
                selectedSpu: null,
                /**
                 *{
                     *  _id,
                     *  name
                     * }
                 */
                selected_specs: {},
                list: [],
                total: 0,
                loading: false,
                showFilter: ''
            }
        },

        computed: {
            canLoadMore: function () {
                return this.list.length < this.total;
            },

            selectedCate: function () {
                if (this.mainCate.subCate && this.mainCate.subCate._id)
                    return this.mainCate.subCate;

                if (this.mainCate._id)
                    return this.mainCate;

                return null;
            }
        },

        attached: function () {
            this.initData();

            this.$nextTick(function(){
                if (positionCache[this.$route.path]) {
                    window.scrollTo(0, positionCache[this.$route.path]);
                }
            })
        },

        detached: function () {
            clearInterval(loadMoreTask);

            console.log('detached');
        },

        destroy: function () {
            console.log('destroy');
        },

        methods: {
            initData:function(refresh) {
//                if (!this.$route.params.refresh || refresh)
//                    return;
//                this.$route.params.refresh = false;

                if (this.$route.params.spu && this.$route.params.spu != 0) {
                    this.selectedSpu = {
                        name: decodeURIComponent(this.$route.params.spu_name),
                        _id: this.$route.params.spu
                    }

                } else {

                    if (this.$route.params.category && this.$route.params.category != 0) {
                        this.mainCate._id = this.$route.params.category;
                        this.mainCate.name = decodeURIComponent(this.$route.params.category_name);
                    }

                    if (this.$route.params.brand && this.$route.params.brand != 0) {
                        this.selectedBrand._id = this.$route.params.brand;
                        this.selectedBrand.name = decodeURIComponent(this.$route.params.brand_name);
                    }

                }
                this.getData(true);
            },

            startLoadMoreTask: function () {
                var self = this;
                if (loadMoreTask)
                    clearInterval(loadMoreTask);

                loadMoreTask = setInterval(function () {
                    if (window.scrollY + db.h - self.doms.topW.scrollHeight < -200 || self.loading)return;

                    if (self.canLoadMore) {
                        self.getData();
                    } else {
                        clearInterval(loadMoreTask);
                    }
                }, 300);
            },

            getData: function (refresh) {
                var self = this;

                self.loading = true;

                var index;
                if (refresh) {
                    index = 0;
                } else
                    index = self.list.length;

                var condition = {
                    limit: 10,
                    index: index
                };

                if (this.selectedSpu) {
                    condition.spu_id = this.selectedSpu._id;
                } else {

                    if (this.selectedCate)
                        condition.category_id = this.selectedCate._id;
                    if (this.selectedBrand._id)
                        condition.brand_id = this.selectedBrand._id;
                }

                if (this.selected_specs) {

                    condition.specs = [];

                    var spec_id, specvalue_id;
                    for (spec_id in this.selected_specs) {
                        specvalue_id = this.selected_specs[spec_id];
                        condition.specs.push({spec_id: spec_id, specvalue_id: specvalue_id,});

                    }


                    if (condition.specs.length == 0)
                        delete condition.specs;
                }


                http.get({
                            url: api + 'commodity/list',
                            jsonp: true,
                            data: condition
                        })
                        .then(function (obj) {
                            if (obj.code == 0) {

                                if (refresh)
                                    self.list = obj.data.list || [];
                                else
                                    self.list = self.list.concat(obj.data.list);

                                self.total = obj.data.count;

                                self.loading = false;

                                //如果是刷新的话要重启loadMoreTask
                                if (refresh) {
                                    self.startLoadMoreTask();

                                    if (secKillTimer)
                                        clearInterval(secKillTimer);

                                    secKillTimer = setInterval(function () {
                                        var isFinish = true;
                                        self.list.forEach(function (secKill) {
                                            if (secKill.time_kill > 0) {
                                                secKill.time_kill -= 1000;
                                                isFinish = false;
                                            }
                                        });
                                        if (isFinish)
                                            clearInterval(secKillTimer);
                                    }, 1000);
                                }
                            } else {
                                alert(obj.msg);
                            }
                        }).catch(function () {
                    self.loading = false;
                })

            },

            //关闭选择阴影
            shadeClose: function () {
                this.showFilter = '';
            },
            //改变了分类
            changeCate: function (selectedCate) {

                this.mainCate = {
                    _id: selectedCate._id,
                    name: selectedCate.name,
                    subCate: {
                        _id: selectedCate.subCate?selectedCate.subCate._id:'',
                        name: selectedCate.subCate?selectedCate.subCate.name:''
                    }
                };

                this.changeBrand();

                this.finishSelectFilter();
            },

            //改变了分类
            changeBrand: function (selectedBrand) {
                if (!selectedBrand)
                    selectedBrand = {};

                this.selectedBrand = selectedBrand;
                this.finishSelectFilter();
            },

            changeDetail: function (selected_specs) {
                if (!selected_specs)
                    selected_specs = {};

                this.selected_specs = selected_specs;
                this.finishSelectFilter();
            },

            //结束选择
            finishSelectFilter: function () {
                this.shadeClose();
                this.getData(true);
                window.scrollTo(0, 0);
            },


            getSecKillDateStr: function (secKill) {
                var nextD = new Date();
                nextD.setDate(nextD.getDate() + 1);
                nextD.setMinutes(0);
                nextD.setHours(0);
                nextD.setSeconds(0);

                var curr = Date.now();

                var startT = curr + secKill.time_kill;
                var isInCurrDay = startT < nextD.getTime();

                if (isInCurrDay) {
                    return timeFormat(secKill.time_kill, 'hh:mm:ss后开始');
                } else {
                    return dateFormat(startT, 'MM月dd日h点开始')
                }
            }
        }

    };

    ['cate', 'brand', 'detail'].forEach(function (method) {
        vm.methods['toggle_' + method] = function () {
            var filter = method + 'Filter';

            if (this.showFilter == filter) {
                this.showFilter = null; //关闭自己
            } else {
                this.showFilter = filter; //切换为自己
            }

        }
    });


    export default vm;
</script>

<style scoped>

    .ui-shade {
        z-index: 10;
        transition: opacity 0.3s;
        -webkit-transition: opacity 0.3s;
    }

    .header-holder {
        height: 36px;
    }

    header {
        height: 36px;
        font-size: 14px;
        position: fixed;
        top: 0;
        width: 100%;
        background: white;
        border-bottom: solid 1px #f0f0f0;
        z-index: 11;
    }

    header h1 {
        font-weight: lighter;
        font-size: 14px;
        width: 80%;
        float: left;
        height: 36px;
        line-height: 36px;
        padding: 0 5%;
    }

    header .tab {
        opacity: 0.6;
        float: left;
        text-align: center;
        width: 45%;
        height: 100%;
    }

    header i {
        float: left;
        text-align: center;
        width: 10%;
        height: 100%;
        background: url(../../static/img/ic_filter.png) no-repeat center;
        background-size: 14px;
    }

    .tab > span {
        vertical-align: middle;
    }

    .tab::after {
        content: '';
        display: inline-block;
        height: 100%;
        width: 8px;
        margin: 0 4px;
        vertical-align: middle;
        background: url(../../static/img/ic_arrow_down.png) no-repeat center;
        background-size: 8px;
    }

    /*.tab.select::after {*/
    /*background-image: url(img/ic_arrow_up.png);*/
    /*}*/

    .tab.active {
        opacity: 1;
    }

    .product {
        width: 100%;
        height: 100px;
        padding: 8px 0;
        background: white;
        border-top: solid 1px #f0f0f0;
    }

    .product > img {
        margin-left: 8px;
        display: block;
        position: absolute;
        width: 100px;
        height: 100px;
    }

    .product > div {
        margin-right: 8px;
        margin-left: 116px;
    }

    .product h1 {
        font-size: 13px;
        width: 210px;
        font-weight: lighter;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }

    .tag:first-child {
        padding: 2px;
        font-size: 10px;
        color: white;
        background: #ffba00;
    }

    .tag {
        padding: 2px;
        font-size: 10px;
        color: #888888;
        background: #eeeeee;
    }

    b.seckill {
        padding: 2px;
        font-size: 10px;
        color: white;
        background: red;
        display: inline-block;
        margin-right: 2px;
        font-weight: lighter;
    }

    .tag-timer::before {
        content: '';
        display: inline-block;
        width: 10px;
        height: 100%;
        background: url(../../static/img/ic_clock.png) no-repeat center;
        background-size: contain;
        margin: 0 2px;
        vertical-align: middle;
    }

    .tag-timer > span {
        vertical-align: middle;
    }

    .tag-timer {
        display: inline-block;
        font-size: 10px;
        height: 16px;
        padding: 0 4px 0 2px;
    }

    .tag-timer {
        color: white;
        background: rgba(0, 0, 0, 0.7);

    }

    .thum-price {
        position: absolute;
        text-align: right;
        right: 8px;
        margin-top: 80px;
    }

    .price-red {
        color: #ff0000;
        font-size: 14px;
        font-weight: normal;
    }

    .price-gray {
        color: #888888;
        text-decoration: line-through;
        font-size: 11px;
    }

    .tips {
        text-align: center;
        font-size: 12px;
        color: #888888;
        padding: 8px;
    }

    .specs {
        font-size: 10px;
        color: #888888;
        position: absolute;
        margin-top: 80px;
    }

    .spec {
        display: inline-block;
        padding: 2px;
    }

    footer {
        display: none;
        transition: bottom 0.3s;
        -webkit-transition: bottom 0.3s;
    }


</style>